package com.unionpay.upyzt.example;

import com.unionpay.upyzt.Upyzt;
import com.unionpay.upyzt.exception.UpyztException;
import com.unionpay.upyzt.model.Payment;
import com.unionpay.upyzt.resp.PaymentResp;

import java.time.OffsetDateTime;
import java.util.HashMap;
import java.util.Map;

public class PaymentExample {

    public PaymentExample(String payBalanceAcctId, String recvBalanceAcctId) {
        this.payBalanceAcctId = payBalanceAcctId;
        this.recvBalanceAcctId = recvBalanceAcctId;
    }

    protected String payBalanceAcctId;

    protected String recvBalanceAcctId;


    /**
     * 运行 Demos
     *
     * @param payBalanceAcctId  付款方电子账簿ID
     * @param recvBalanceAcctId 收款方电子账簿ID
     * @return 消费（转账）对象
     */
    public static PaymentResp runDemos(String payBalanceAcctId, String recvBalanceAcctId) throws UpyztException {
        PaymentExample paymentExample = new PaymentExample(payBalanceAcctId, recvBalanceAcctId);

        // 消费（转账）
        PaymentResp paymentResp = paymentExample.create();

        // 消费（转账）订单查询（系统订单号）
        paymentResp = paymentExample.retrieveById(paymentResp.getPaymentId());

        // 消费（转账）订单查询（平台订单号）
        paymentResp = paymentExample.retrieveByOutOrderNo(paymentResp.getOutOrderNo());

        return paymentResp;
    }

    /**
     * 消费（转账）
     *
     * @return 返回参数
     * @throws UpyztException 异常
     */
    public PaymentResp create() throws UpyztException {
        Map<String, Object> params = new HashMap<>();
        params.put("out_order_no", Main.generateRandomOutNo());
        params.put("sent_at", OffsetDateTime.now().toString());
        params.put("amount", 10);
        params.put("pay_balance_acct_id", this.payBalanceAcctId);
        params.put("recv_balance_acct_id", this.recvBalanceAcctId);
        params.put("password", Upyzt.encryptField("pa55w0rd"));
        params.put("remark", "用于 SDK 示例测试");
        params.put("metadata", MockData.metadata());
        params.put("extra", MockData.extra());
        System.out.println("------- 消费（转账） -------");
        PaymentResp resp = Payment.create(params);
        System.out.println(resp);
        return resp;
    }

    /**
     * 消费（转账）订单查询（系统订单号）
     *
     * @return 返回参数
     * @throws UpyztException 异常
     */
    public PaymentResp retrieveById(String id) throws UpyztException {
        System.out.println("------- 消费（转账）订单查询（系统订单号） -------");
        PaymentResp resp = Payment.retrieveById(id);
        System.out.println(resp);
        return resp;
    }

    /**
     * 消费（转账）订单查询（平台订单号）
     *
     * @return 返回参数
     * @throws UpyztException 异常
     */
    public PaymentResp retrieveByOutOrderNo(String outOrderNo) throws UpyztException {
        System.out.println("------- 消费（转账）订单查询（平台订单号） -------");
        PaymentResp resp = Payment.retrieveByOutOrderNo(outOrderNo);
        System.out.println(resp);
        return resp;
    }

}
